import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { signInAPI } from '../../services/api';

// 获取待签到任务
export const fetchPendingTasks = createAsyncThunk(
  'signIn/fetchPendingTasks',
  async (_, { rejectWithValue }) => {
    try {
      const response = await signInAPI.getTasks();
      if (response.data && (response.data.code === 2000 || response.data.code === 200 || response.data.code === 0)) {
        return response.data.data || [];
      } else {
        return rejectWithValue(response.data.message || '获取签到任务失败');
      }
    } catch (error) {
      return rejectWithValue(error.message || '网络错误');
    }
  }
);

// 执行签到
export const performSignIn = createAsyncThunk(
  'signIn/performSignIn',
  async (signInData, { rejectWithValue }) => {
    try {
      const response = await signInAPI.signIn(signInData);
      if (response.data && (response.data.code === 2000 || response.data.code === 200 || response.data.code === 0)) {
        return response.data;
      } else {
        return rejectWithValue(response.data.message || '签到失败');
      }
    } catch (error) {
      return rejectWithValue(error.message || '网络错误');
    }
  }
);

// 获取签到历史
export const fetchSignInHistory = createAsyncThunk(
  'signIn/fetchSignInHistory',
  async (params = { forceRefresh: false, showMissed: true }, { rejectWithValue, getState, signal }) => {
    try {
      // 检查是否已经有历史数据，可选择不重复请求
      const { history } = getState().signIn;
      
      // 如果已有数据并且没有传入强制刷新标志，直接返回
      if (history && history.length > 0 && !params.forceRefresh) {
        return history;
      }
      
      // 添加取消请求能力，防止多个请求同时发出
      const controller = new AbortController();
      signal.addEventListener('abort', () => controller.abort());
      
      const response = await signInAPI.getHistory(params.showMissed);
      
      console.log('获取签到历史响应:', response);
      
      // 处理不同格式的响应
      if (response.data && (response.data.code === 2000 || response.data.code === 200 || response.data.code === 0)) {
        // 检查data字段的格式
        let historyData = [];
        
        if (Array.isArray(response.data.data)) {
          historyData = response.data.data;
        } else if (response.data.data && typeof response.data.data === 'object') {
          // 如果data是对象但不是数组，可能包含在records或其他字段中
          if (Array.isArray(response.data.data.records)) {
            historyData = response.data.data.records;
          } else {
            // 尝试将对象转为数组
            historyData = [response.data.data];
          }
        }
        
        // 确保每条记录都有sign_in_time字段，对于未签到的记录使用end_time
        historyData = historyData.map(record => {
          if (!record.sign_in_time && record.end_time) {
            return {
              ...record,
              sign_in_time: record.end_time
            };
          }
          return record;
        });
        
        console.log('处理后的历史数据:', historyData);
        return historyData;
      }
      
      return rejectWithValue(response.data?.message || '获取历史失败');
    } catch (error) {
      // 对于已取消的请求，返回特殊标记
      if (error.name === 'CanceledError' || error.code === 'ERR_CANCELED') {
        return rejectWithValue('canceled');
      }
      
      console.error('获取签到历史失败:', error);
      return rejectWithValue(error.response?.data?.message || error.message || '获取历史失败');
    }
  },
  {
    // 添加条件选项，如果已有数据则不重复请求
    condition: (_, { getState }) => {
      const { loading } = getState().signIn;
      // 如果已在加载中，不重复请求
      if (loading) {
        return false;
      }
      return true;
    }
  }
);

const signInSlice = createSlice({
  name: 'signIn',
  initialState: {
    pendingTasks: [],
    history: [],
    loading: false,
    error: null,
    signInSuccess: false,
  },
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
    resetSignInStatus: (state) => {
      state.signInSuccess = false;
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取待签到任务
      .addCase(fetchPendingTasks.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPendingTasks.fulfilled, (state, action) => {
        state.loading = false;
        state.pendingTasks = action.payload;
      })
      .addCase(fetchPendingTasks.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload || '获取签到任务失败';
      })
      
      // 执行签到
      .addCase(performSignIn.pending, (state) => {
        state.loading = true;
        state.error = null;
        state.signInSuccess = false;
      })
      .addCase(performSignIn.fulfilled, (state) => {
        state.loading = false;
        state.signInSuccess = true;
      })
      .addCase(performSignIn.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload || '签到失败';
        state.signInSuccess = false;
      })
      
      // 获取签到历史
      .addCase(fetchSignInHistory.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchSignInHistory.fulfilled, (state, action) => {
        state.loading = false;
        state.error = null;
        state.history = action.payload || [];
      })
      .addCase(fetchSignInHistory.rejected, (state, action) => {
        state.loading = false;
        if (action.error && action.error.name === 'CanceledError') {
          return;
        }
        state.error = action.payload;
      });
  },
});

export const { clearError, resetSignInStatus } = signInSlice.actions;
export default signInSlice.reducer;